<template>
  <div>
    <v-row>
      <v-col cols="12" sm="6" md="4" lg="3">
        <v-hover v-slot:default="{ hover }">
        <v-card :disabled="multiple ? files.length === maximum : files.length === 1 " :elevation="hover ? 12 : 2">
          <!-- <v-card-text> -->
            <v-input
            height="160"
            :messages="inputMessages"
            :error="false"
            :error-messages="inputErrorMessages"
            :error-count="inputMsgCount">
              <file-upload
              style="width:100%;"
              :multiple="multiple"
              :maximum="maximum"
              ref="upload"
              v-model="files"
              :headers="headers"
              :post-action="SingleImageUploadApi"
              put-action=""
              :size="maxSize"
              :extensions="allowExt"
              @input-file="inputFile"
              @input-filter="inputFilter"
              :data="{water: water, module: moduleName}"
              >
                <v-btn block height="160" ><v-icon>add_photo_alternate</v-icon>
                {{files.length === maximum ? '已经够了': '点击上传'}}</v-btn>
                </file-upload>
            </v-input>
        <!-- </v-card-text>-->
        <v-card-actions>
          <!-- <v-checkbox disabled class="mt-0" hide-details :label="water ? '添加水印' : '不加水印'" color="primary" v-model="water"></v-checkbox> -->
        </v-card-actions>
        </v-card>
        </v-hover>
      </v-col>
      <v-col  cols="12" sm="6" md="4" lg="3" v-for="(item, index) in tmpValue" :key="item">
        <v-card class="lighten-2">
          <v-img :src="item" height="160"></v-img>
          <v-card-actions>
            <v-row justify="space-around" dense>
              <v-col><v-btn depressed block small color="info" @click.stop="preview = item"><v-icon small>zoom_in</v-icon>预览</v-btn></v-col>
              <v-col>
                <template v-if="index > 0">
                  <v-btn depressed block small color="success" @click="setCoverFile(item, index)"><v-icon small>photo</v-icon>设置封面</v-btn>
                </template>
                <template v-else>
                  <v-btn depressed readonly block small color="teal" class="darken-2" dark ><v-icon small>photo</v-icon>封面</v-btn>
                </template>
              </v-col>
              <v-col><v-btn depressed block small color="warning" @click="deleteFile(index)"><v-icon small>delete</v-icon>删除</v-btn></v-col>
            </v-row>
          </v-card-actions>
        </v-card>
      </v-col>
      <v-col  cols="12" sm="6" md="4" lg="3" v-for="(item) in files" :key="item.id">
        <v-card :loading="item.active" color="success" class="lighten-2">
          <v-img :src="item.response.url" height="160"></v-img>
        </v-card>
      </v-col>
    </v-row>
    <ImagePreview v-model="preview"/>
  </div>
</template>
<script>
import VueUploadComponent from 'vue-upload-component'
import { SingleImageUploadApi } from '@/api/attachment'
import CustomFunc from '@/mixin/func.js'
import ImagePreview from './ImagePreview.vue'
export default {
  name: 'ImageUpload',
  props: {
    moduleName: {
      type: String,
      default: 'common'
    },
    label: {
      type: String,
      default: '图片上传'
    },
    hint: {
      type: String,
      default: ''
    },
    value: {
      type: Array,
      default: () => { return [] }
    },
    cover: {
      type: String,
      default: null
    },
    maxSize: {
      type: Number,
      default: 10 * 1024 * 1024
    },
    allowExt: {
      type: Array,
      default: () => { return ['jpeg', 'jpe', 'jpg', 'gif', 'png', 'webp'] }
    },
    multiple: {
      type: Boolean,
      default: true
    },
    maximum: {
      type: Number,
      default: 10
    }
  },
  mixins: [ CustomFunc ],
  components: {
    'FileUpload': VueUploadComponent,
    ImagePreview
  },
  data() {
    return {
      water: false,
      files: [],
      tmpValue: this.value || [],
      inputErrorMessages: [], // 错误消息
      preview: null,
      SingleImageUploadApi // 文件上传地址
    }
  },
  computed: {
    inputMessages: function() {
      return [
        '最多只能上传' + (this.multiple ? this.maximum : 1) + '张图片!'
        // '最大只能上传' + this.calcSize(this.maxSize) + '大小的图片'
      ] // 消息
    },
    inputError: function() {
      return this.inputErrorMessages.length > 0
    },
    inputMsgCount: function() {
      return Math.max(this.inputErrorMessages.length, this.inputMessages.length)
    },
    headers: function () {
      // return { 'Authorization': 'Bearer ' + this.$store.getters.token }
      return { 'Authorization': 'Bearer ' + this.$store.getters.token }
    }
  },
  methods: {
    clearErrorMessage: function() {
      this.inputErrorMessages = []
    },
    updateValue: function() {
      if (this.$refs.upload && this.$refs.upload.uploaded) {
        this.$emit('input', this.tmpValue)
        if (this.cover === null || this.cover === '') {
          this.$emit('update:cover', this.tmpValue[0])
        }
        this.clearErrorMessage()
      }
    },
    deleteFile: function(index) {
      this.tmpValue.splice(index, 1)
      this.updateValue()
    },
    setCoverFile: function(url, index) {
      // this.files.forEach(e => (e.response.is_cover = false))
      // item.response.is_cover = true
      // this.updateValue()
      if (index <= 0) {
        return false
      } else {
        this.tmpValue.splice(index, 1)
        this.tmpValue.unshift(url)
        this.$emit('update:cover', url)
        this.$emit('input', this.tmpValue)
        this.updateValue()
      }
    },
    /**
     * Has changed
     * @param  Object|undefined   newFile   只读
     * @param  Object|undefined   oldFile   只读
     * @return undefined
     */
    inputFile: function(newFile, oldFile) {
      // 自动上传
      if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
        if (!this.$refs.upload.active) {
          this.$refs.upload.active = true
        }
      }
      // 添加文件
      if (newFile && !oldFile) {
        // 添加文件
      }
      // 更新文件
      if (newFile && oldFile) {
        // 上传成功
        if (newFile.success !== oldFile.success) {
          this.tmpValue.push(newFile.response.url)
          this.updateValue()
          this.files.shift()
        }
        // 上传错误
        if (newFile.error !== oldFile.error) {
          this.files.shift()
          this.inputErrorMessages.push('发生' + newFile.error + '错误')
        }
      }
    },
    /**
     * Pretreatment
     * @param  Object|undefined   newFile   读写
     * @param  Object|undefined   oldFile   只读
     * @param  Function           prevent   阻止回调
     * @return undefined
     */
    inputFilter: function (newFile, oldFile, prevent) {
      if (newFile && !oldFile) {
        const extStr = this.allowExt.join('|')
        const regExp = new RegExp('\\.(' + extStr + ')$', 'i')
        // eslint-disable-next-line
        if (!regExp.test(newFile.name)) {
          this.inputErrorMessages.push('不允许的上传类型！只允许上传' + extStr + '类型的图片文件')
          return prevent()
        }
        if (newFile.size > (this.maxSize)) {
          this.inputErrorMessages.push('图片尺寸过大(文件大小：' + this.calcSize(newFile.size) + ')！请选择文件大小为' + this.calcSize(this.maxSize) + '以下的图片进行上传！')
          return prevent()
        }
        // 判断个数
        if (this.multiple && this.files.length === this.maximum) {
          this.inputErrorMessages.push('最多上传' + this.maximum + '张图片！')
          return prevent()
        } else if (!this.multiple && this.files.length === 1) {
          this.inputErrorMessages.push('只能上传一张图片！')
          return prevent()
        }
      }
    }
  }
}
</script>
<style>
.v-messages__wrapper{
  padding: 0 10px 0 10px;
}
</style>
